#include "qrender.h"

#include "Core/Debugger/Debugger.h"
#include "Core/Shared/EmuSettings.h"
#include "Core/Shared/Emulator.h"
#include "Core/Shared/MessageManager.h"
#include "Core/Shared/RenderedFrame.h"
#include "Core/Shared/Video/VideoDecoder.h"
#include "Core/Shared/Video/VideoRenderer.h"

#include <QDebug>

QRender::QRender(Emulator *emu)
    : m_emulator(emu)
    , m_requredWidth(256)
    , m_requredHeight(240)
    , m_frameImage(m_requredWidth, m_requredHeight, QImage::Format_ARGB32_Premultiplied)
{
    emu->GetVideoRenderer()->RegisterRenderingDevice(this);
}

QRender::~QRender()
{
}

void QRender::UpdateFrame(RenderedFrame &frame)
{
    if (m_requredWidth != frame.Width || m_requredHeight != frame.Height) {
        m_requredWidth = frame.Width;
        m_requredHeight = frame.Height;
        m_frameImage = QImage(m_requredWidth, m_requredHeight, QImage::Format_ARGB32_Premultiplied);
    }

    if (frame.FrameBuffer) {
        memcpy(m_frameImage.bits(), frame.FrameBuffer, frame.Width * frame.Height * 4);
    } else {
        m_frameImage.fill(Qt::black); // Fill with black if no framebuffer is provided
    }

    Q_EMIT frameUpdated(m_frameImage);
}

void QRender::ClearFrame()
{
    m_frameImage.fill(Qt::black); // Clear the frame image
    Q_EMIT frameUpdated(m_frameImage);
}

void QRender::Render(RenderSurfaceInfo &emuHud, RenderSurfaceInfo &scriptHud)
{
    Q_UNUSED(emuHud);
    Q_UNUSED(scriptHud);
}

void QRender::Reset()
{
    // reset and initialize the renderer
    // m_requredWidth = 256;
    // m_requredHeight = 240;
    m_frameImage = QImage(m_requredWidth, m_requredHeight, QImage::Format_ARGB32_Premultiplied);
    m_frameImage.fill(Qt::black); // Clear the frame image

    m_emulator->GetVideoRenderer()->RegisterRenderingDevice(this);
}

void QRender::OnRendererThreadStarted()
{
    Reset();
}

void QRender::SetExclusiveFullscreenMode(bool fullscreen, void *windowHandle)
{
    Q_UNUSED(fullscreen);
    Q_UNUSED(windowHandle);
}
